﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="StrategyContainerControl.cs" company="">
//   
// </copyright>
// <summary>
//   The strategy container control.
// </summary>
// --------------------------------------------------------------------------------------------------------------------


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Objects;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Runtime.Serialization.Formatters.Soap;
using System.Threading;
using System.Windows.Forms;
using Systemathics.FrameWork;
using Systemathics.UserControls.Properties;

namespace Systemathics.UserControls
{
    [ToolboxBitmap(typeof (StrategyContainerControl), "UserControlsIcon.bmp")]
    public sealed partial class StrategyContainerControl : UserControl
    {
        private EngineParametersBox epb;
        private InstrumentContainerControl InstrumentManager;
        private BackOfficeControl BackOffice;
        private RemotingLogClient RemotingClient;
        private readonly Image signal;
        private readonly Image signal_5;
        private Form ProvidersForm, BackOfficeForm, InstrumentsForm;
        private StrategyPool Pool;
        private StrategyMode strategyMode;
        private readonly Dictionary<Guid, List<String>> AllInstrumentsPerStrategy;
        private readonly List<StaticData> AllInstrumentsInDictionnary;
        private delegate void InvokeDelegate(FireMessageEventArgs e);
        private delegate void LaunchDelegate();
        private SystemathicsSound sounds;
        private Pattern[] allPatterns;
        public event EventHandler OnStrategySelected;
        public Strategy Strategy { get; private set; }
        private SystemathicsEntities db;

        

        public StrategyContainerControl()
        {
            InitializeComponent();
            DoubleBuffered = true;
            signal = Image.FromHbitmap(Resources.Signal.GetHbitmap());
            signal_5 = Image.FromHbitmap(Resources.Signal_5.GetHbitmap());
            StatusStrip.Dock = DockStyle.Bottom;

            BackTesttoolStripButton.CheckedChanged += BackTesttoolStripButtonCheckedChanged;
            VirtualtoolStripButton.CheckedChanged += VirtualtoolStripButtonCheckedChanged;
            ProdtoolStripButton.CheckedChanged += ProdtoolStripButtonCheckedChanged;

            Thread.CurrentThread.CurrentCulture = GlobalVariables.SystemathicsCulture();
            AllInstrumentsPerStrategy = new Dictionary<Guid, List<string>>();
            epb = new EngineParametersBox();
            AllInstrumentsInDictionnary = new List<StaticData>();
            sounds = new SystemathicsSound();
            db = new SystemathicsEntities(GlobalVariables.EntitiesConnectionString());
            StrategyDataGridView.CellFormatting += StrategyDataGridViewCellFormatting;
            var instantiateAllInstruments = new BackgroundWorker();
            instantiateAllInstruments.DoWork += InstantiateAllInstrumentsDoWork;
            instantiateAllInstruments.RunWorkerAsync();
        }
        private void StrategyContainerControl_Load(object sender, EventArgs e)
        {
            Dock = DockStyle.Fill;
            if (ParentForm != null)
            {
                ParentForm.Icon = Icon.FromHandle(Resources.MSN_Mobile.GetHicon());
                ParentForm.Name = "Strategies Container";
                ParentForm.ShowIcon = true;
                ParentForm.SizeGripStyle = SizeGripStyle.Hide;
                ParentForm.MaximizeBox = true;
                ParentForm.MinimizeBox = true;
                ParentForm.StartPosition = FormStartPosition.CenterScreen;
                ParentForm.FormBorderStyle = FormBorderStyle.Sizable;
                ParentForm.ControlBox = true;
                ParentForm.Opacity = 0.9;
                ParentForm.FormClosing += ParentFormFormClosing;
                ParentForm.Resize += ParentFormResize;
            }

            var exitItem = new MenuItem { Index = 0, Text = "E&xit Strat Container" };
            var borderItem = new MenuItem { Index = 0, Text = "H&ide/Show Borders" };
            borderItem.Click += BorderItemClick;
            exitItem.Click += MenuItemClick;

            var menu = new ContextMenu();
            menu.MenuItems.Add(borderItem);
            menu.MenuItems.Add(exitItem);

            notifyIcon1.Icon = Icon.FromHandle(Resources.MSN_Mobile.GetHicon());
            notifyIcon1.ContextMenu = menu;
            notifyIcon1.Text = "Strategy Container";
            notifyIcon1.Visible = true;
            notifyIcon1.Click += NotiftyIconClick;

            notifyIcon1.BalloonTipText = "Systemathics Trading Application Loaded";
            notifyIcon1.ShowBalloonTip(1000);
            //var pLaunchDelegate = new LaunchDelegate(BigWorkAtLaucnh);
            //pLaunchDelegate.BeginInvoke(null, null);

        }

        private void InstantiateAllInstrumentsDoWork(object sender, DoWorkEventArgs e)
        {
            const string settingsFileName = "Parameters.xml";
            var isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);
            if (isoStore.GetFileNames(settingsFileName).Length != 0)
            {
                var stream = new IsolatedStorageFileStream(settingsFileName, FileMode.Open, FileAccess.Read, isoStore);
                if (stream != null)
                {
                    try
                    {
                        var SF = new SoapFormatter();
                        epb = (EngineParametersBox)SF.Deserialize(stream);
                        ProvidersForm.Close();
                    }
                    catch (Exception ex)
                    {
                    }
                    finally
                    {
                        stream.Close();
                    }
                }
            }
            RemotingClient = new RemotingLogClient();
            InstrumentManager = new InstrumentContainerControl();
            BackOffice = new BackOfficeControl();
            //LoadAllInstrumentsStaticData();
            allPatterns = ProviderFactory.GetStrategiesPattern(GlobalVariables.AUTOMATES);
            foreach (var strategiese in db.DBStrategies.Take(db.DBStrategies.Count()))
            {
                strategiese.DBInstruments.Load();
                foreach (var instrument in strategiese.DBInstruments)
                {
                    var sd = new StaticData(instrument);
                    sd.LoadCurrency();
                    sd.LoadExchange();
                    sd.LoadRules();
                    AllInstrumentsInDictionnary.Add(sd);
                    instrument.DBFees.Load();
                }
            }
        }

        private void BigWorkAtLaucnh()
        {
           
        }

        private void LoadAllInstrumentsStaticData()
        {
            foreach (var dbi in db.DBInstruments.Select(i => i))
                AllInstrumentsInDictionnary.Add(new StaticData(dbi));
            RemotingClient.Trace(new FireMessageEventArgs(AllInstrumentsInDictionnary.Count + " Instruments loaded", Time.Now.TimeOfDay));
        }
        public void MenuItemClick(object sender, EventArgs e)
        {
            notifyIcon1.Dispose();
            if (ParentForm != null) ParentForm.Close();
        }
        private bool IsAnyStrategyRunning
        {
            get
            {
                if (Pool != null)
                {
                    var finalState = false;
                    foreach (var kvp in Pool.StrategiesAssembly)
                        finalState = finalState | kvp.Value.isRunning;
                    return finalState;
                }
                return false;
            }
        }
        private void BorderItemClick(object sender, EventArgs e)
        {
            if (ParentForm != null)
                if (ParentForm.FormBorderStyle == FormBorderStyle.Sizable)
                {
                    ParentForm.FormBorderStyle = FormBorderStyle.None;
                    ParentForm.ControlBox = false;
                }
                else
                {
                    ParentForm.FormBorderStyle = FormBorderStyle.Sizable;
                    ParentForm.ControlBox = true;
                }
        }
        private void NotiftyIconClick(object sender, EventArgs e)
        {
            if (ParentForm != null)
            {
                if (ParentForm.WindowState == FormWindowState.Minimized)
                {
                    ParentForm.Show();
                    ParentForm.WindowState = FormWindowState.Normal;
                }

                ParentForm.Activate();
            }
        }
        private void ParentFormResize(object sender, EventArgs e)
        {
            if (ParentForm != null)
                if (ParentForm.WindowState == FormWindowState.Minimized)
                    ParentForm.Hide();
        }
        private void ParentFormFormClosing(object sender, FormClosingEventArgs e)
        {
            if (Pool != null)
            {
                Pool.StrategyPoolOnConnection -= StrategyPoolStrategyPoolOnConnection;
                Pool.StrategyPoolEmitError -= StrategyPoolStrategyPoolEmitError;
            }

            notifyIcon1.Dispose();
        }
        private void BackOfficeToolStripButton_Click(object sender, EventArgs e)
        {
            if (BackOfficeForm == null)
            {
                BackOfficeForm = new Form { Size = new Size(800, 400), Text = "Back Office" };
                BackOfficeForm.Closed += BackOfficeFormClosed;
                BackOfficeForm.Controls.Add(BackOffice);
                BackOfficeForm.Show();
            }
        }
        private void BackOfficeFormClosed(object sender, EventArgs e)
        {
            BackOfficeForm.Controls.Remove(BackOffice);
            BackOfficeForm.Dispose();
            BackOfficeForm = null;
        }
        private void RecorderToolStripButtonClick(object sender, EventArgs e)
        {
            if (InstrumentsForm == null)
            {
                InstrumentsForm = new Form {Size = new Size(800, 400), Text = "Instrument Manager"};
                InstrumentsForm.Closed += RecorderFormClosed;
                InstrumentsForm.Controls.Add(InstrumentManager);
                InstrumentsForm.Show();
            }
        }
        private void RecorderFormClosed(object sender, EventArgs e)
        {
            InstrumentsForm.Controls.Remove(InstrumentManager);
            InstrumentsForm.Dispose();
            InstrumentsForm = null;
        }
        private void StrategyPoolStrategyPoolOnConnection(object sender, FireMessageEventArgs e)
        {
            StatusStrip.BeginInvoke(new InvokeDelegate(StatusChanged), e);
        }
        private void StrategyPoolStrategyPoolEmitError(object sender, FireMessageEventArgs e)
        {
            RemotingClient.Trace(e);
        }
        private void StatusChanged(FireMessageEventArgs e)
        {
            var cs = (ConnectionStatus) e.Message;
            switch (cs)
            {
                case ConnectionStatus.Connected:
                    Enabled = true;
                    sounds.CONNECTED();

                    if (strategyMode == StrategyMode.BackTest)
                    {
                        BackTesttoolStripButton.Image = Resources.quick_restart;
                        VirtualtoolStripButton.Enabled = false;
                        ProdtoolStripButton.Enabled = false;
                    }
                    else if (strategyMode == StrategyMode.Virtual)
                    {
                        VirtualtoolStripButton.Image = Resources.quick_restart;
                        BackTesttoolStripButton.Enabled = false;
                        ProdtoolStripButton.Enabled = false;
                    }
                    else if (strategyMode == StrategyMode.Live)
                    {
                        ProdtoolStripButton.Image = Resources.quick_restart;
                        BackTesttoolStripButton.Enabled = false;
                        VirtualtoolStripButton.Enabled = false;
                    }

                    ToolStripStatusLabel.Text = strategyMode.ToString();
                    ToolStripStatusLabel.Image = signal_5;
                    if (strategyMode != StrategyMode.BackTest)
                    {
                        InstrumentManager.DataService = Pool.dataService;
                        BackOffice.DataService = Pool.dataService;
                        BackOffice.OrderService = Pool.orderService;
                        InstrumentToolStripButton.Enabled = true;
                        ChartToolStripButton.Enabled = true;
                        BackOfficeToolStripButton.Enabled = true;
                    }

                    break;
                case ConnectionStatus.Disconnected:
                    sounds.DISCONNECTED();
                    
                    if (strategyMode == StrategyMode.BackTest)
                        BackTesttoolStripButton.Image = Resources.exit;
                    else if (strategyMode == StrategyMode.Virtual)
                        VirtualtoolStripButton.Image = Resources.exit;
                    else if (strategyMode == StrategyMode.Live)
                        ProdtoolStripButton.Image = Resources.exit;

                    BackTesttoolStripButton.Enabled = true;
                    VirtualtoolStripButton.Enabled = true;
                    ProdtoolStripButton.Enabled = true;
                    ToolStripStatusLabel.Text = "Wires Disconnected";
                    ToolStripStatusLabel.Image = signal;

                    if (strategyMode != StrategyMode.BackTest)
                    {
                        InstrumentToolStripButton.Enabled = false;
                        ChartToolStripButton.Enabled = false;
                        BackOfficeToolStripButton.Enabled = false;
                    }
                    break;
                default:
                    break;
            }
        }
        private void AddStrategy_Click(object sender, EventArgs e)
        {
            if (Pool != null)
            {
                if (Pool.isConnected)
                {
                    if (allPatterns.Count() > 0)
                    {
                        var o = new AddStrategyForm(AllInstrumentsInDictionnary) { StrategiesPattern = allPatterns };
                        if (o.ShowDialog() == DialogResult.OK && Pool != null)
                        {
                            dBStrategiesBindingSource.DataSource = db.DBStrategies.Execute(MergeOption.OverwriteChanges);
                            ToolStripStatusLabel.ForeColor = Color.Black;
                            ToolStripStatusLabel.Text = "Strategy updated";
                            ToolStripButtonRemove.Enabled = true;
                        }
                        else
                            ToolStripStatusLabel.Text = "This Strat doesn't contains any instruments";
                    }
                    else
                        ToolStripStatusLabel.Text = "No Strategy Assembly present in Automation Folder";
                }
                else
                    ToolStripStatusLabel.Text = "Set up Connection First";
            }
            else
                ToolStripStatusLabel.Text = "Connection failed or not started up";
               
        }
        private void EdittoolStripButton_Click(object sender, EventArgs e)
        {
            if (StrategyDataGridView.CurrentRow != null)
            {
                var cell = StrategyDataGridView.CurrentRow.DataBoundItem as DBStrategies;
                if (!Pool.ContainsStrategyKey(cell.ID))
                {
                    Pool.BuildUp(cell);
                    Pool.StrategiesAssembly[cell.ID].RemoteLogClient = RemotingClient;
                }
                var strategy = Pool.StrategiesAssembly[cell.ID];

                if (!strategy.isRunning)
                {
                    var o = new AddStrategyForm(AllInstrumentsInDictionnary)
                                {
                                    StrategiesPattern = allPatterns,
                                    Strategy = cell
                                };

                    if (o.ShowDialog() == DialogResult.OK)
                        dBStrategiesBindingSource.DataSource = db.DBStrategies.Execute(MergeOption.OverwriteChanges);
                }
                else
                    ToolStripStatusLabel.Text = "ITS FORBIDDEN TO EDIT/CHANGE STRATEGY DETAILS WHILE ITS RUNNING, Stop it First !!!!";
            }
        }
        private void RemoveStrategy_Click(object sender, EventArgs e)
        {
            if (StrategyDataGridView.Rows.Count > 0)
            {
                foreach (DataGridViewRow dvr in StrategyDataGridView.SelectedRows)
                {
                    var Id = (Guid)dvr.Cells["ID"].Value;
                    if(Pool.ContainsStrategyKey(Id))
                    {
                        if (!Pool.StrategiesAssembly[Id].isRunning)
                        {
                            Pool.Remove(Id);
                            StrategyDataGridView.Rows.Remove(dvr);
                            AllInstrumentsPerStrategy[Id].Clear();
                            AllInstrumentsPerStrategy.Remove(Id);
                        }
                        else
                            ToolStripStatusLabel.Text = "Stop this strategy before removing it";   
                    }
                }
            }
        }
        private void UpdateStartStopDataGridView(object sender, FireMessageEventArgs e)
        {
            foreach (DataGridViewRow dvr in StrategyDataGridView.Rows)
            {
                var Id = (Guid)dvr.Cells["ID"].Value;
                if (Pool.ContainsStrategyKey(Id))
                {
                    if (Pool.StrategiesAssembly[Id].isRunning)
                    {
                        Pool.StrategiesAssembly[Id].OnStop();
                        dvr.Cells["Status"].Value = Resources.Hors_ligne;
                        dvr.Cells["StartStop"].Value = "Stopped";
                        dvr.Cells["StartStop"].Style.BackColor = Color.Red;
                        dvr.Cells["StartStop"].Style.SelectionBackColor = Color.Red;
                    }   
                }
            }
        }
        private void EngineParameterstoolStripButton_Click(object sender, EventArgs e)
        {
            const string settingsFileName = "Parameters.xml";
            var isoStore = IsolatedStorageFile.GetStore( IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null );
            var propertyGrid = new PropertyGrid { Dock = DockStyle.Fill, SelectedObject = epb };
            ProvidersForm = new Form { Size = new Size(400, 300) };
            var SaveButton = new Button
            {
                Dock = DockStyle.Bottom,
                Text = "Save Settings",
                DialogResult = DialogResult.OK
            };
            ProvidersForm.Text = "Engine Parameters";
            ProvidersForm.Icon = Icon.FromHandle(Resources.MSN_Mobile.GetHicon());
            ProvidersForm.Controls.Add(propertyGrid);
            ProvidersForm.Controls.Add(SaveButton);
            if (ProvidersForm.ShowDialog() == DialogResult.OK)
            {
                epb = propertyGrid.SelectedObject as EngineParametersBox;
                var stream = new IsolatedStorageFileStream(settingsFileName, FileMode.OpenOrCreate, FileAccess.Write, isoStore);
                var SF = new SoapFormatter();
                SF.Serialize(stream, epb);
                stream.Close();
                isoStore.Close();
                ProvidersForm.Close();
            }
        }
        private void dataGridViewStrategy_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (Pool != null)
            {
                if (Pool.isConnected && e.RowIndex >= 0 && StrategyDataGridView.Rows.Count > 0)
                {
                    var currentStrat = StrategyDataGridView.CurrentRow.DataBoundItem as DBStrategies;
                    if(!Pool.ContainsStrategyKey(currentStrat.ID))
                    {
                        Pool.BuildUp(currentStrat);
                        Pool.StrategiesAssembly[currentStrat.ID].RemoteLogClient = RemotingClient;
                    }

                    Strategy = Pool.StrategiesAssembly[currentStrat.ID];
                    
                    if (StrategyDataGridView.Columns[e.ColumnIndex].Name == "StartStop")
                    {
                        if (!Strategy.isRunning)
                        {
                            Strategy.OnStart();

                            if (Strategy.isRunning)
                            {
                                StrategyDataGridView.CurrentRow.Cells["Status"].Value = Resources.En_ligne;
                                ((DataGridViewButtonCell)StrategyDataGridView.Rows[e.RowIndex].Cells["StartStop"]).UseColumnTextForButtonValue = false;
                                StrategyDataGridView.Rows[e.RowIndex].Cells["StartStop"].Value = "Started";
                                StrategyDataGridView.Rows[e.RowIndex].Cells["StartStop"].Style.BackColor = Color.LimeGreen;
                                StrategyDataGridView.Rows[e.RowIndex].Cells["StartStop"].Style.SelectionBackColor = Color.LimeGreen;

                                if (Strategy.dataService.Name == StrategyMode.BackTest.ToString())
                                {
                                    var backTestCannotStart = (bool)Strategy.dataService.DataProvider.GetType().GetProperty("StrategyMustBeDisconnected").GetValue(Strategy.dataService.DataProvider, null);
                                    if (!backTestCannotStart)
                                    {
                                        // Strategy.isPaused = false;
                                        Strategy.dataService.DataProvider.GetType().GetMethod("StartTheBackTest").Invoke(Strategy.dataService.DataProvider, null);
                                    }
                                    else
                                    {
                                        Strategy.OnStop();
                                        StrategyDataGridView.CurrentRow.Cells["Status"].Value = Resources.Hors_ligne;
                                        ((DataGridViewButtonCell)StrategyDataGridView.Rows[e.RowIndex].Cells["StartStop"]).UseColumnTextForButtonValue = false;
                                        StrategyDataGridView.Rows[e.RowIndex].Cells["StartStop"].Value = "Stopped";
                                        StrategyDataGridView.Rows[e.RowIndex].Cells["StartStop"].Style.BackColor = Color.Red;
                                        StrategyDataGridView.Rows[e.RowIndex].Cells["StartStop"].Style.SelectionBackColor = Color.Red;
                                    }
                                }
                            }
                            else
                            {
                                Strategy.OnStop();
                                StrategyDataGridView.CurrentRow.Cells["Status"].Value = Resources.Hors_ligne;
                                ((DataGridViewButtonCell)StrategyDataGridView.Rows[e.RowIndex].Cells["StartStop"]).UseColumnTextForButtonValue = false;
                                StrategyDataGridView.Rows[e.RowIndex].Cells["StartStop"].Value = "Stopped";
                                StrategyDataGridView.Rows[e.RowIndex].Cells["StartStop"].Style.BackColor = Color.Red;
                                StrategyDataGridView.Rows[e.RowIndex].Cells["StartStop"].Style.SelectionBackColor = Color.Red;
                            }
                        }
                        else if (Strategy.isRunning)
                        {
                            if (Strategy[Expo.Working].NetExposedNominal != 0)
                            {
                                if (MessageBox.Show("Strategy has Working orders on the market. Do You want to stop Anyway ?", "Stop Strategy", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                                    return;
                            }
                            Strategy.OnStop();
                            if (!Strategy.isRunning)
                            {
                                StrategyDataGridView.CurrentRow.Cells["Status"].Value = Resources.Hors_ligne;
                                ((DataGridViewButtonCell)StrategyDataGridView.Rows[e.RowIndex].Cells["StartStop"]).UseColumnTextForButtonValue = false;
                                StrategyDataGridView.Rows[e.RowIndex].Cells["StartStop"].Value = "Stopped";
                                StrategyDataGridView.Rows[e.RowIndex].Cells["StartStop"].Style.BackColor = Color.Red;
                                StrategyDataGridView.Rows[e.RowIndex].Cells["StartStop"].Style.SelectionBackColor = Color.Red;
                            }
                            ///////////////////////////Strategy.Dispose();
                        }
                        //OnStrategySelected(this, new EventArgs());
                    }
                    else if (StrategyDataGridView.Columns[e.ColumnIndex].Name == "PlayPause")
                    {
                        if (Strategy.isConnected)
                        {
                            if (Strategy.isPaused)
                            {
                                ((DataGridViewButtonCell)StrategyDataGridView.Rows[e.RowIndex].Cells["PlayPause"]).UseColumnTextForButtonValue = false;
                                StrategyDataGridView.Rows[e.RowIndex].Cells["PlayPause"].Value = "Playing";
                                StrategyDataGridView.Rows[e.RowIndex].Cells["PlayPause"].Style.BackColor = Color.LimeGreen;
                                StrategyDataGridView.Rows[e.RowIndex].Cells["PlayPause"].Style.SelectionBackColor = Color.LimeGreen;
                                StrategyDataGridView.Rows[e.RowIndex].Cells["PlayPause"].ToolTipText = "OrderService Enabled";
                                Strategy.isPaused = false;
                            }
                            else 
                            {
                                ((DataGridViewButtonCell)StrategyDataGridView.Rows[e.RowIndex].Cells["PlayPause"]).UseColumnTextForButtonValue = false;
                                StrategyDataGridView.Rows[e.RowIndex].Cells["PlayPause"].Value = "Paused";
                                StrategyDataGridView.Rows[e.RowIndex].Cells["PlayPause"].Style.BackColor = Color.Red;
                                StrategyDataGridView.Rows[e.RowIndex].Cells["PlayPause"].Style.SelectionBackColor = Color.Red;
                                StrategyDataGridView.Rows[e.RowIndex].Cells["PlayPause"].ToolTipText = "OrderService Disabled";
                                Strategy.isPaused = true;
                            }
                        }
                    }
                    else if (Strategy.isRunning)
                        OnStrategySelected(this, new EventArgs());
                }
            }
        }
        public void UpdateStrategyContainer()
        {
            if (Pool != null)
            {
                foreach (DataGridViewRow row in StrategyDataGridView.Rows)
                {
                    var key = new Guid(row.Cells["Id"].Value.ToString());

                    row.Cells["Bias"].Value = Pool.StrategiesAssembly[key].Bias * 100;
                    row.Cells["DD"].Value = Pool.StrategiesAssembly[key].DrawDown * 100;
                    row.Cells["Profit"].Value = Pool.StrategiesAssembly[key].NetPl_Traded;
                    row.Cells["CashEquity"].Value = Pool.StrategiesAssembly[key].CashEquity;
                }
            }
        }
        private void StrategyDataGridViewCellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.RowIndex < StrategyDataGridView.RowCount)
            {
                if (StrategyDataGridView.CurrentRow != null)
                {
                    var Id = new Guid(StrategyDataGridView.CurrentRow.Cells["ID"].Value.ToString());
                    if(AllInstrumentsPerStrategy.ContainsKey(Id))
                    {
                        var s = "Strategy Instrument's: \n\n";
                        foreach (var name in AllInstrumentsPerStrategy[Id])
                            s += string.Format("- {0}\n ", name);
                        StrategyDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].ToolTipText = s;
                    }
                }
            }
        }
        private void ChartToolStripButton_Click(object sender, EventArgs e)
        {
            Process.Start(GlobalVariables.ASSEMBLY + "\\Systemathics.Applications.Chart.exe");
        }
        private void LogToolStripButton_Click(object sender, EventArgs e)
        {
            Process.Start(GlobalVariables.ASSEMBLY + "\\Systemathics.Applications.Log.exe");
        }
        private void ParameterstoolStripButton_Click(object sender, EventArgs e)
        {
            Process.Start(GlobalVariables.PARAMETERS);
        }
        private void BackTesttoolStripButtonCheckedChanged(object sender, EventArgs e)
        {
            StartTheBusiness(sender, StrategyMode.BackTest, StrategyMode.BackTest.ToString(), StrategyMode.Virtual.ToString(), epb.FeesProvider);
        }
        private void VirtualtoolStripButtonCheckedChanged(object sender, EventArgs e)
        {
            StartTheBusiness(sender, StrategyMode.Virtual, epb.VirtualMarketProvider, StrategyMode.Virtual.ToString(), epb.FeesProvider);
        }
        private void ProdtoolStripButtonCheckedChanged(object sender, EventArgs e)
        {
            StartTheBusiness(sender, StrategyMode.Live, epb.LiveDataProvider, epb.LiveOrderProvider, epb.FeesProvider);
        }
        private void StartTheBusiness(object sender, StrategyMode mode, String PipeIn, String PipeOut, String FeesProvider)
        {
            if (IsHandleCreated)
            {
                if (!String.IsNullOrEmpty(PipeIn) && !String.IsNullOrEmpty(PipeOut) && !String.IsNullOrEmpty(FeesProvider))
                {
                    if (!IsAnyStrategyRunning)
                    {
                        var bt = sender as ToolStripButton;
                        if (bt.CheckState == CheckState.Checked)
                        {
                            Enabled = false;
                            if (!IsAnyStrategyRunning)
                            {
                                Pool = new StrategyPool(PipeIn, PipeOut, FeesProvider);
                                if (Pool != null)
                                {
                                    strategyMode = mode;
                                    if (mode == StrategyMode.Virtual)
                                    {
                                        Pool.VMP = new VirtualMarketParameters
                                        {
                                            AckDelay = epb.AckDelay,
                                            HITorTAKEProbability = epb.HITorTAKEProbability,
                                            MinimumHitRatioProbability = epb.MinimumHitRatioProbability,
                                            RejectionProbability = epb.RejectionProbability
                                        };
                                    }
                                    else if (mode == StrategyMode.BackTest)
                                    {
                                        Delegate handler = new EventHandler<FireMessageEventArgs>(UpdateStartStopDataGridView);
                                        Pool.dataService.DataProvider.GetType().GetEvent("OnBackTestDisconnected").AddEventHandler(Pool.dataService.DataProvider, handler);
                                        Pool.VMP = new VirtualMarketParameters
                                        {
                                            AckDelay = epb.AckDelay,
                                            HITorTAKEProbability = epb.HITorTAKEProbability,
                                            MinimumHitRatioProbability = epb.MinimumHitRatioProbability,
                                            RejectionProbability = epb.RejectionProbability
                                        };
                                    }
                                    Pool.StrategyPoolOnConnection += StrategyPoolStrategyPoolOnConnection;
                                    Pool.StrategyPoolEmitError += StrategyPoolStrategyPoolEmitError;
                                    Pool.Connect();

                                    if (Pool.isConnected)
                                    {
                                        dBStrategiesBindingSource.DataSource = db.DBStrategies.Execute(MergeOption.OverwriteChanges);
                                        ToolStripStatusLabel.ForeColor = Color.Black;
                                        ToolStripStatusLabel.Text = "Strategies Loaded";
                                        ToolStripButtonRemove.Enabled = true;
                                    }
                                }
                            }
                            bt.CheckState = CheckState.Indeterminate;
                        }
                        else if (bt.CheckState == CheckState.Unchecked)
                        {
                            if (Pool != null && Pool.orderService != null)
                            {
                                if (Pool.isConnected)
                                {
                                    UpdateStartStopDataGridView(this, new FireMessageEventArgs(ConnectionStatus.Disconnected, Time.Now.TimeOfDay));
                                    Pool.Disconnect();
                                    Pool.StrategyPoolOnConnection -= StrategyPoolStrategyPoolOnConnection;
                                    Pool.StrategyPoolEmitError -= StrategyPoolStrategyPoolEmitError;
                                    Pool.Dispose();
                                    Pool = null;
                                }
                                AllInstrumentsPerStrategy.Clear();
                            }
                            bt.CheckState = CheckState.Unchecked;
                        }
                    }
                    else
                        ToolStripStatusLabel.Text = "Disconnect all strategies before shuting down";
                }
                else
                    ToolStripStatusLabel.Text = "Engine parameters seems empty!";
           }
        }
    }
}